package br.upe.dsc.patdown.control;

import java.util.Hashtable;
import java.util.Map;

import br.upe.dsc.patdown.data.WorkerFailureInfo;

public class PDController {

	private Map<Object, Integer> amountNotifications;
	private Map<String, String> mapOriginalReplica; // maps original worker's
													// public key to its
													// replica.
	private Map<String, Object> mapWorkerOldJob; // maps worker's public key to
													// its main running job.

	private Map<Long, WorkerFailureInfo> mapFailures;
	
	private static PDController instance;

	public static boolean IS_DEBUG;
	
	private PDController() {
		this.amountNotifications = new Hashtable<Object, Integer>();
		this.mapOriginalReplica = new Hashtable<String, String>();
		this.mapWorkerOldJob = new Hashtable<String, Object>();
		this.mapFailures = new Hashtable<Long, WorkerFailureInfo>();
	}

	public void workerFailed(String workerKey, String brokerKey, long requestId){
		WorkerFailureInfo failureInfo = new WorkerFailureInfo(workerKey, brokerKey, requestId);
		mapFailures.put(requestId, failureInfo);
	}
	
	public boolean containsRequest(long requestId){
		return mapFailures.containsKey(requestId);
	}
	
	public WorkerFailureInfo getFailureInfo(long requestId){
		return mapFailures.get(requestId);
	}
	
	
	public void workerFailed(String worker, int jobID) {
		this.mapWorkerOldJob.put(worker, jobID);
	}

	public int getJobExecution(String workerPublicKey) {
		if (mapWorkerOldJob.containsKey(workerPublicKey)) {
			return (Integer) mapWorkerOldJob.get(workerPublicKey);
		} else {
			return 0;
		}
	}

	
	public boolean shouldNotifyFailure(Object serviceID) {
		if (amountNotifications.containsKey(serviceID)) {

			Integer numberComplaints = amountNotifications.get(serviceID);
			System.out.println("Called " + numberComplaints + " times. - " + serviceID.toString());
			if (numberComplaints > 10) {
				return true;
			} else {
				numberComplaints++;
				amountNotifications.put(serviceID, numberComplaints);
				return false;
			}
		} else {
			amountNotifications.put(serviceID, 0);
			return false;
		}
	}

	public static PDController getInstance() {
		if (instance == null) {
			instance = new PDController();
		}
		return instance;
	}

}
